#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/7/30 10:55
# @Author  : XH
# @File    : generate_dataclass_code.py
# @Software: PyCharm
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set
# 后续字段有代码注释再扩展
# FIELD_COMMENTS = {
#     "orderConvertingStepId": "订单工序ID",
#     "pullCount": "拉动次数",
#     "orderRunInfoId": "订单运行ID",
#     "convertingMachineNo": "加工设备编号",
#     "freightTrips": "运输车次",
#     "addToTail": "是否加入队尾"
# }
@dataclass
class ClassField:
    name: str #字段名
    type_hint: str #字段类型提示
    default: str #默认值字符串
    comment: Optional[str] = None #字段注释


class JsonToDataclassConverter:
    def __init__(self, json_file: str, root_class_name: str, out_file: str):
        self.json_file = json_file
        self.root_class_name = root_class_name
        self.out_file = out_file #可修改自动生成的文件名
        self.class_defs: Dict[str, List[ClassField]] = {}
        self.generated_classes: Set[str] = set()

    def convert(self):
        with open(self.json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)

        self._parse_dict(self.root_class_name, data)
        #output_file = self._generate_output_file_name()
        self._write_classes()

    def _parse_dict(self, class_name: str, data: Dict[str, Any]):
        if class_name in self.generated_classes:
            return
        fields: List[ClassField] = []
        for key, value in data.items():
            field_type, default_val = self._infer_type_and_default(key, value)
            #comment = FIELD_COMMENTS.get(key)
            #fields.append(ClassField(name=key, type_hint=field_type, default=default_val, comment=comment))
            fields.append(ClassField(name=key, type_hint=field_type, default=default_val))
        self.class_defs[class_name] = fields
        self.generated_classes.add(class_name)

    def _infer_type_and_default(self, key: str, value: Any):
        if isinstance(value, str):
            return "str", "field(default='')"
        elif isinstance(value, int):
            return "int", "field(default=0)"
        elif isinstance(value, bool):
            return "bool", "field(default=False)"
        elif value is None:
            return "Optional[str]", "field(default=None)"
        elif isinstance(value, list):
            if len(value) == 0:
                return "List", "field(default_factory=list)"
            first = value[0]
            if isinstance(first, dict):
                sub_class_name = self._capitalize_singular(key)
                self._parse_dict(sub_class_name, first)
                return f"List[{sub_class_name}]", f"field(default_factory=lambda: [{sub_class_name}()])"
            else:
                return f"List[{type(first).__name__}]", "field(default_factory=list)"
        elif isinstance(value, dict):
            sub_class_name = self._capitalize_singular(key)
            self._parse_dict(sub_class_name, value)
            return sub_class_name, f"field(default_factory={sub_class_name})"
        else:
            return "Any", "field(default=None)"

    def _capitalize_singular(self, name: str):
        return ''.join(part.capitalize() for part in name.rstrip('s').split('_'))
    #自动生成文件名，取消自定义
    # def _generate_output_file_name(self):
    #     def snake_case(name: str):
    #         return ''.join(['_' + c.lower() if c.isupper() else c for c in name]).lstrip('_')
    #
    #     return f"{snake_case(self.root_class_name)}.py"

    def _write_classes(self):
        with open(self.out_file, 'w', encoding='utf-8') as f:
            f.write("from dataclasses import dataclass, field\n")
            f.write("from typing import List, Optional, Any\n\n")

            #for class_name, fields in reversed(list(self.class_defs.items())):
            for class_name, fields in list(self.class_defs.items()):
                f.write(f"@dataclass\nclass {class_name}:\n")
                for field in fields:
                    #comment = f"  # {field.comment}" if field.comment else ""
                    #f.write(f"    {field.name}: {field.type_hint} = {field.default}{comment}\n")
                    f.write(f"    {field.name}: {field.type_hint} = {field.default}\n")
                f.write("\n")


if __name__ == "__main__":
    json_file = "9_.json"
    root_class_name = "OrderRunInfoAddData"
    output_file = "order_run_info_add_data.py"

    converter = JsonToDataclassConverter(json_file, root_class_name, output_file)
    converter.convert()
    print(f"✅ 数据类代码已生成到: {output_file}")



